package com.example.sprintboot.service;

import com.example.sprintboot.entity.Interaction;
import com.example.sprintboot.mapper.InteractionMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户交互服务类
 */
@Service
public class InteractionService {

    @Autowired
    private InteractionMapper interactionMapper;

    /**
     * 交互类型常量
     */
    public static final int TYPE_LIKE = 1;      // 点赞
    public static final int TYPE_VIEW = 2;      // 浏览
    public static final int TYPE_FAVORITE = 3;  // 收藏
    public static final int TYPE_RATING = 4;    // 评分

    /**
     * 根据ID查询交互记录
     */
    public Interaction getById(Integer id) {
        return interactionMapper.selectById(id);
    }

    /**
     * 查询所有交互记录
     */
    public List<Interaction> getAll() {
        return interactionMapper.selectAll();
    }

    /**
     * 根据用户ID查询交互记录
     */
    public List<Interaction> getByUserId(Integer userId) {
        return interactionMapper.selectByUserId(userId);
    }

    /**
     * 根据内容查询交互记录
     */
    public List<Interaction> getByContent(String contentType, Integer contentId) {
        return interactionMapper.selectByContent(contentType, contentId);
    }

    /**
     * 检查用户是否已经对内容进行过某种交互
     */
    public boolean hasUserInteracted(Integer userId, String contentType, Integer contentId, Integer type) {
        Interaction interaction = interactionMapper.selectUserInteraction(userId, contentType, contentId, type);
        return interaction != null;
    }

    /**
     * 用户点赞/取消点赞
     */
    public boolean toggleLike(Integer userId, String contentType, Integer contentId) {
        return toggleInteraction(userId, contentType, contentId, TYPE_LIKE, 0);
    }

    /**
     * 记录用户浏览
     */
    public boolean recordView(Integer userId, String contentType, Integer contentId) {
        // 浏览可以重复记录，所以直接添加
        Interaction interaction = new Interaction();
        interaction.setUserId(userId);
        interaction.setContentType(contentType);
        interaction.setContentId(contentId);
        interaction.setType(TYPE_VIEW);
        interaction.setScore(0);
        interaction.setCreateTime(LocalDateTime.now());
        
        return interactionMapper.insert(interaction) > 0;
    }

    /**
     * 用户收藏/取消收藏
     */
    public boolean toggleFavorite(Integer userId, String contentType, Integer contentId) {
        return toggleInteraction(userId, contentType, contentId, TYPE_FAVORITE, 0);
    }

    /**
     * 用户评分
     */
    public boolean rateContent(Integer userId, String contentType, Integer contentId, Integer score) {
        if (score < 1 || score > 5) {
            throw new IllegalArgumentException("评分必须在1-5之间");
        }

        // 检查是否已经评分
        Interaction existing = interactionMapper.selectUserInteraction(userId, contentType, contentId, TYPE_RATING);
        
        if (existing != null) {
            // 更新评分
            existing.setScore(score);
            return interactionMapper.update(existing) > 0;
        } else {
            // 新增评分
            Interaction interaction = new Interaction();
            interaction.setUserId(userId);
            interaction.setContentType(contentType);
            interaction.setContentId(contentId);
            interaction.setType(TYPE_RATING);
            interaction.setScore(score);
            interaction.setCreateTime(LocalDateTime.now());
            
            return interactionMapper.insert(interaction) > 0;
        }
    }

    /**
     * 切换交互状态（点赞、收藏等）
     */
    private boolean toggleInteraction(Integer userId, String contentType, Integer contentId, Integer type, Integer score) {
        Interaction existing = interactionMapper.selectUserInteraction(userId, contentType, contentId, type);
        
        if (existing != null) {
            // 已存在，删除（取消操作）
            return interactionMapper.deleteUserInteraction(userId, contentType, contentId, type) > 0;
        } else {
            // 不存在，添加
            Interaction interaction = new Interaction();
            interaction.setUserId(userId);
            interaction.setContentType(contentType);
            interaction.setContentId(contentId);
            interaction.setType(type);
            interaction.setScore(score);
            interaction.setCreateTime(LocalDateTime.now());
            
            return interactionMapper.insert(interaction) > 0;
        }
    }

    /**
     * 删除交互记录
     */
    public boolean deleteById(Integer id) {
        return interactionMapper.deleteById(id) > 0;
    }

    /**
     * 获取内容的统计信息
     */
    public Map<String, Object> getContentStatistics(String contentType, Integer contentId) {
        Map<String, Object> stats = new HashMap<>();
        
        stats.put("likes", interactionMapper.getLikeCount(contentType, contentId));
        stats.put("views", interactionMapper.getViewCount(contentType, contentId));
        stats.put("favorites", interactionMapper.getFavoriteCount(contentType, contentId));
        
        Double avgRating = interactionMapper.getAverageRating(contentType, contentId);
        stats.put("averageRating", avgRating != null ? Math.round(avgRating * 10.0) / 10.0 : 0.0);
        
        List<Map<String, Object>> ratingStats = interactionMapper.getRatingStatistics(contentType, contentId);
        stats.put("ratingDistribution", ratingStats);
        
        return stats;
    }

    /**
     * 获取用户活跃度统计
     */
    public Map<String, Object> getUserActivityStatistics(Integer userId) {
        Map<String, Object> stats = new HashMap<>();
        
        List<Map<String, Object>> activities = interactionMapper.getUserActivityStatistics(userId);
        stats.put("activities", activities);
        
        int totalInteractions = interactionMapper.countByUserId(userId);
        stats.put("totalInteractions", totalInteractions);
        
        return stats;
    }

    /**
     * 获取热门内容
     */
    public List<Map<String, Object>> getPopularContent(String contentType, Integer limit) {
        return interactionMapper.getPopularContent(contentType, limit);
    }

    /**
     * 获取用户推荐内容
     */
    public List<Map<String, Object>> getRecommendedContent(Integer userId, Integer limit) {
        return interactionMapper.getRecommendedContent(userId, limit);
    }

    /**
     * 分页查询所有交互记录
     */
    public PageInfo<Interaction> getByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Interaction> list = interactionMapper.selectAll();
        return PageInfo.of(list);
    }

    /**
     * 分页查询用户交互记录
     */
    public PageInfo<Interaction> getUserInteractionsByPage(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Interaction> list = interactionMapper.selectByUserId(userId);
        return PageInfo.of(list);
    }

    /**
     * 分页查询内容交互记录
     */
    public PageInfo<Interaction> getContentInteractionsByPage(String contentType, Integer contentId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Interaction> list = interactionMapper.selectByContent(contentType, contentId);
        return PageInfo.of(list);
    }

    /**
     * 分页查询指定类型的交互记录
     */
    public PageInfo<Interaction> getInteractionsByTypeWithPage(Integer type, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Interaction> list = interactionMapper.selectByType(type);
        return PageInfo.of(list);
    }

    /**
     * 条件分页查询
     */
    public PageInfo<Interaction> searchByCondition(Integer userId, String contentType, Integer contentId, 
                                                 Integer type, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Interaction> list = interactionMapper.selectByCondition(userId, contentType, contentId, type, null, null);
        return PageInfo.of(list);
    }

    /**
     * 统计总数
     */
    public int count() {
        return interactionMapper.count();
    }

    /**
     * 获取用户对内容的交互状态
     */
    public Map<String, Object> getUserInteractionStatus(Integer userId, String contentType, Integer contentId) {
        Map<String, Object> status = new HashMap<>();
        
        status.put("hasLiked", hasUserInteracted(userId, contentType, contentId, TYPE_LIKE));
        status.put("hasFavorited", hasUserInteracted(userId, contentType, contentId, TYPE_FAVORITE));
        
        // 获取用户评分
        Interaction rating = interactionMapper.selectUserInteraction(userId, contentType, contentId, TYPE_RATING);
        status.put("userRating", rating != null ? rating.getScore() : 0);
        
        return status;
    }

    /**
     * 批量记录浏览
     */
    public int batchRecordViews(Integer userId, String contentType, List<Integer> contentIds) {
        int count = 0;
        for (Integer contentId : contentIds) {
            if (recordView(userId, contentType, contentId)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 获取交互类型名称
     */
    public String getInteractionTypeName(Integer type) {
        switch (type) {
            case TYPE_LIKE: return "点赞";
            case TYPE_VIEW: return "浏览";
            case TYPE_FAVORITE: return "收藏";
            case TYPE_RATING: return "评分";
            default: return "未知";
        }
    }
}